/**
 * @author flq
 * 
 */

function Snake(){
	this.body = [];
	this.speed = 0;
	this.dir = 0; //方向 0 1 2 3 上右下左
	this.gameEngine = null;
}
Snake.prototype = {
	init :function(){
		this.gameEngine = new GameEngine();
		this.speed = 500;
		//随机位置出现
		var site = {
			X: randomUtils.int(this.gameEngine.ROWS/4,this.gameEngine.ROWS*3/4),
			Y : randomUtils.int(this.gameEngine.COLS/4,this.gameEngine.COLS*3/4)
		}
		this.body.push(site);
		//显示
		this.show().move();
		return this;
	},
	show:function(){
		var _this = this;
		this.body.forEach(function(item,index,arr){
			_this.gameEngine._table.children[item.X].children[item.Y].className= "snakeBody";
		});
		
		return this;
	},
	move:function(){
		this._interval = setInterval(function(){
			
			this.nextStep();
			this.show();
		}.bind(this),this.speed);
	},
	nextStep:function(){
		var nextSite = null;
		switch(this.dir){ 
			case 0: nextSite={X:this.body[0].X-1,Y:this.body[0].Y};break;
			case 1: nextSite={X:this.body[0].X,Y:this.body[0].Y+1};break;
			case 2: nextSite={X:this.body[0].X+1,Y:this.body[0].Y};break;
			case 3: nextSite={X:this.body[0].X,Y:this.body[0].Y-1};break; 
		}
		if(nextSite.X<0 || nextSite.Y<0|| nextSite.Y>=this.gameEngine.COLS|| nextSite.X >= this.gameEngine.ROWS){/*撞墙*/
			clearInterval(this._interval);
			this.gameEngine.stop();
		}else if(this.gameEngine._table.children[nextSite.X].children[nextSite.Y].className == 'snakeBody'){/*吃自己*/
			clearInterval(this._interval);
			this.gameEngine.stop();
		}else if(this.gameEngine._table.children[nextSite.X].children[nextSite.Y].className == 'food'){
			this.gameEngine.addFood();
			this.body.unshift(nextSite);
		}else{
			var last = this.body.pop();
			this.gameEngine._table.children[last.X].children[last.Y].className = "";
			this.body.unshift(nextSite);
		}
		
	}
}







